package com.zhufeng.jvm.classloader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyTest16 extends ClassLoader {

	private String loaderName;

	private String loadPath;

	private final String fileExtension = ".class";

	public MyTest16(String loaderName) {
		super(); // 使用系统应用加载器作为父类加载器
		this.loaderName = loaderName;
	}

	public MyTest16(String loaderName, ClassLoader classLoader) {
		super(classLoader);
		this.loaderName = loaderName;
	}
	
	public void setLoadPath(String loadPath) {
		this.loadPath = loadPath;
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		System.out.println(loaderName + " findClass: " + name);
		byte[] data = loadClassData(name);
		return this.defineClass(name, data, 0, data.length);
	}

	private byte[] loadClassData(String name) {
		InputStream io = null;
		ByteArrayOutputStream baos = null;
		int len = 0;

		try {
			String fileName = name.replace(".", "/");
			io = new FileInputStream(loadPath + fileName + fileExtension);
			baos = new ByteArrayOutputStream();

			while (-1 != (len = io.read())) {
				baos.write(len);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				io.close();
				baos.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		return baos.toByteArray();
	}

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		MyTest16 load16 = new MyTest16("load16");
		load16.setLoadPath("/Users/zhufeng/Desktop/");
		Class<?> clazz = load16.loadClass("com.zhufeng.jvm.classloader.MyTest2");
		System.out.println(clazz.hashCode());
		System.out.println(clazz.newInstance());
		
		System.out.println("==================================================");
		
		MyTest16 load17 = new MyTest16("load17");
		load17.setLoadPath("/Users/zhufeng/Desktop/");
		Class<?> clazz2 = load17.loadClass("com.zhufeng.jvm.classloader.MyTest2");
		System.out.println(clazz2.hashCode());
		System.out.println(clazz2.newInstance());
	}

}
